﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.Models;
using App.Models.Pager;
using App.Views.ViewModels;
using BLL;

namespace App.Controllers
{
    public class VehicleServiceController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult List(int? page, int? rows, string order)
        {
            dbe.ContextOptions.ProxyCreationEnabled = false;
            dbe.ContextOptions.LazyLoadingEnabled = false;

            PagedList<tb_UseVehicleRecords> list = null;
            if ("asc" == order)
            {
                list = dbe.tb_UseVehicleRecords.OrderBy(m => m.UseVehicleNO)
                                .ToPagedList(page ?? 1, rows ?? 10);
            }
            else
            {
                list = dbe.tb_UseVehicleRecords.OrderByDescending(m => m.UseVehicleNO)
                                .ToPagedList(page ?? 1, rows ?? 10);
            }
            PagedList<VehicleServiceEditViewModel> data = new PagedList<VehicleServiceEditViewModel>(
                                                list.CurrentPageIndex, list.PageSize, list.total);
            data.rows.AddRange(from f in list.rows
                               select new VehicleServiceEditViewModel
                               {
                                   UseVehicleNO = f.UseVehicleNO,
                                   VehicleNO = f.VehicleNO,
                                   ServiceNo = f.ServiceNo,
                                   PlanTime = f.PlanTime,
                                   DepartureTime = f.DepartureTime,
                                   ReturnTime = f.ReturnTime,
                                   ContactUnit = f.ContactUnit,
                                   ContactPhone = f.ContactPhone,                                   
                                   Requirements = f.Requirements,
                                   Purpose = f.Purpose,
                                   Remark = f.Remark,
                                   EmployeeNO = f.EmployeeNO,
                                   Charges = f.Charges,
                                   MeetAddress = f.MeetAddress,
                                   SendAddress = f.SendAddress,
                                   MileAge = f.MileAge,
                                   DeadNO = dbe.tb_ServiceDetail.FirstOrDefault(m => m.ServiceNo == f.ServiceNo).DeadNO,                                   
                               });
            return Json(data, JsonRequestBehavior.AllowGet);
        }        
        [HttpPost]
        public ActionResult Create(VehicleServiceEditViewModel vmodel) {

            try
            {
                var serviceNo = GenServiceNo();
                var serviceModel = new tb_ServiceDetail
                {
                    ServiceNo = serviceNo,
                    ApplyTime = DateTime.Now,
                    Salesman = CurrentUser,
                    ItemNO = Utils.VEHICLE_SERVICE_TYPE,
                    ServiceNoParent = serviceNo
                };
                dbe.tb_ServiceDetail.AddObject(serviceModel);

                var model = new tb_UseVehicleRecords
                {
                    UseVehicleNO = GenUseVehicleNO(),
                    ServiceNo = serviceNo,
                    EmployeeNO = vmodel.EmployeeNO,
                    VehicleNO = vmodel.VehicleNO,
                    ContactUnit = vmodel.ContactUnit,
                    ContactPhone = vmodel.ContactPhone,
                    PlanTime = vmodel.PlanTime,
                    MeetAddress = vmodel.MeetAddress,
                    SendAddress = vmodel.SendAddress,
                    Purpose = vmodel.Purpose,
                    Requirements = vmodel.Requirements,
                    Remark = vmodel.Remark
                };
                dbe.tb_UseVehicleRecords.AddObject(model);
                dbe.SaveChanges();
                return Json(new { success = true }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { success = false, msg = "保存出错！" }, JsonRequestBehavior.AllowGet);
            } 
        }
        
        [HttpPost]
        public ActionResult Edit(string id,VehicleServiceEditViewModel vmodel)
        {
            try
            {
                var model = dbe.tb_UseVehicleRecords.FirstOrDefault(m => m.UseVehicleNO == id);
                model.EmployeeNO = vmodel.EmployeeNO;
                model.VehicleNO = vmodel.VehicleNO;
                model.ContactUnit = vmodel.ContactUnit;
                model.ContactPhone = vmodel.ContactPhone;
                model.PlanTime = vmodel.PlanTime;
                model.MeetAddress = vmodel.MeetAddress;
                model.SendAddress = vmodel.SendAddress;
                model.Purpose = vmodel.Purpose;
                model.Requirements = vmodel.Requirements;
                model.Remark = vmodel.Remark;
                dbe.SaveChanges();  
                return Json(new { success = true }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { success = false, msg = "保存出错！" }, JsonRequestBehavior.AllowGet);
            } 
        }
        
        [HttpPost]
        public ActionResult Delete(string ids)
        {
            try
            {
                string[] idList = ids.Split('&');
                foreach (var id in idList)
                {
                    var obj = dbe.tb_UseVehicleRecords.FirstOrDefault(m => m.UseVehicleNO == id);
                    dbe.tb_UseVehicleRecords.DeleteObject(obj);
                    //删除服务收费
                    DeleteServiceItems(obj.ServiceNo);
                }

                dbe.SaveChanges();
                var res = new { success = true };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                var res = new { success = false, msg = "删除出错！" };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
        }

        //选择司机
        public ActionResult SelectDriver(string st) {
            //禁止页面被缓存
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Today.AddYears(-2));

            SysPersonBLL bll = new SysPersonBLL();
            var list = bll.GetByDepartment(Utils.DRIVER_DEPARTMENT);
            // m.ReturnTime == null 表示该位置已经预约或在用 
            var useds = dbe.tb_UseVehicleRecords.Where(m => m.ReturnTime == null);
            var usedIdList = useds.Select(m => m.EmployeeNO).ToList();
            var usedList = useds.ToList();
            //预约车辆
            var yys = useds.Where(m => m.DepartureTime == null);
            var yysIdList = yys.Select(m => m.EmployeeNO).ToList();
            var yylist = yys.ToList();

            //已经预约但在此段时间空间的
            //var idles = yys.Where(m => m.PlanTime > EndTime);
            //var idleIdList = idles.Select(m => m.EmployeeNO).ToList();
            //var idlelist = idles.ToList();
            List<DriverVehicleStatusViewModel> dvlist = new List<DriverVehicleStatusViewModel>();
            foreach (var c in list)
            {
                string status = "空闲";
                string hintMsg = "";
                int pos = usedIdList.IndexOf(c.Name);
                if (pos >= 0)
                {
                    status = "在用";
                    hintMsg = string.Format("[{0:yyyy/MM/dd HH:mm}]-[{1:yyyy/MM/dd HH:mm}]", usedList[pos].DepartureTime, usedList[pos].ReturnTime);
                    if (yysIdList.IndexOf(c.Name) >= 0)
                    {  //预约占用
                        status = "在用";
                        hintMsg = string.Format("[{0:yyyy/MM/dd HH:mm}]-[{1:yyyy/MM/dd HH:mm}]", usedList[pos].PlanTime, usedList[pos].ReturnTime);
                    }
                }
                var dvItem = new DriverVehicleStatusViewModel
                {
                    DriverNO = c.Name,
                    DriverName = c.MyName,
                    Status = status,
                    Remark = hintMsg
                };
                dvlist.Add(dvItem);
            }
            return PartialView(dvlist);
        }
        //选择车辆
        public ActionResult SelectVehicle(string st)
        {
            //禁止页面被缓存
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Today.AddYears(-2));  

            var list = dbe.tb_VehicleInfo.ToList();
            // m.ReturnTime == null 表示该位置已经预约或在用 
            var useds = dbe.tb_UseVehicleRecords.Where(m => m.ReturnTime == null);
            var usedIdList = useds.Select(m => m.VehicleNO).ToList();
            var usedList = useds.ToList();
            //预约车辆
            var yys = useds.Where(m => m.DepartureTime == null);
            var yysIdList = yys.Select(m => m.VehicleNO).ToList();
            var yylist = yys.ToList();

            //已经预约但在此段时间空间的
            //var idles = yys.Where(m => m.PlanTime > EndTime);
            //var idleIdList = idles.Select(m => m.VehicleNO).ToList();
            //var idlelist = idles.ToList();
            List<DriverVehicleStatusViewModel> dvlist = new List<DriverVehicleStatusViewModel>();
            foreach (var c in list)
            {
                string status = "空闲";
                
                string hintMsg = "";
                int pos = usedIdList.IndexOf(c.VehicleNO);
                if (pos >= 0)
                {
                    status = "在用";                    
                    hintMsg = string.Format("[{0:yyyy/MM/dd HH:mm}]-[{1:yyyy/MM/dd HH:mm}]", usedList[pos].DepartureTime, usedList[pos].ReturnTime);
                    //if (idleIdList.IndexOf(c.VehicleNO) >= 0)
                    //{      //预约可用
                    //    status = "空闲";
                    //    hintMsg = string.Format("[{0:yyyy/MM/dd HH:mm}]-[{1:yyyy/MM/dd HH:mm}]", idlelist[pos].PlanTime, idlelist[pos].ReturnTime);
                    //    imgIndex = 1;
                    //}
                    //else 
                    if (yysIdList.IndexOf(c.VehicleNO) >= 0)
                    {  //预约占用
                        status = "在用";                        
                        hintMsg = string.Format("[{0:yyyy/MM/dd HH:mm}]-[{1:yyyy/MM/dd HH:mm}]", usedList[pos].PlanTime, usedList[pos].ReturnTime);
                    }
                }
                var dvItem = new DriverVehicleStatusViewModel
                {
                    VehicleNO = c.VehicleNO,
                    Status = status,
                    Remark = hintMsg
                };
                dvlist.Add(dvItem);
            }     
            return PartialView(dvlist);
        }

        //派车，生成派车时间
        public ActionResult StartVehicle(string id) {
            try
            {
                var model = dbe.tb_UseVehicleRecords.FirstOrDefault(m => m.UseVehicleNO == id);
                model.DepartureTime = DateTime.Now;
                dbe.SaveChanges();
                var res = new { success = true,msg = model.DepartureTime };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                var res = new { success = false, msg = "派车失败！" };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
        }

        //还车，生成时间，并填写里程数和运费
        public ActionResult ReturnVehicle(string id, VehicleServiceEditViewModel vmodel)
        {
            var model = dbe.tb_UseVehicleRecords.FirstOrDefault(m => m.UseVehicleNO == id);
            var serviceDetail = dbe.tb_ServiceDetail.FirstOrDefault(m => m.ServiceNo == model.ServiceNo);            
            try
            {
                model.MileAge = vmodel.MileAge;
                model.Charges = vmodel.Charges;
                model.ReturnTime = DateTime.Now;

                serviceDetail.ServiceCount = model.MileAge;
                serviceDetail.ServiceCountBak = model.MileAge;
                serviceDetail.ServiceFee = model.Charges;
                serviceDetail.DeadNO = vmodel.DeadNO;                
                dbe.SaveChanges();
                CurrentDeader = vmodel.DeadNO;
                var res = new { success = true, msg = model.ReturnTime };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                var res = new { success = false, msg = "还车失败！" };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
        }

        //打印派车单
        public ActionResult PrintBill(string id) {
            return View();
        }
        
    }
}
